package cn.ronghuanet.org.service.impl;

import cn.ronghuanet.base.util.PageInfo;
import cn.ronghuanet.org.domain.Department;
import cn.ronghuanet.org.mapper.DepartmentMapper;
import cn.ronghuanet.org.query.DepartmentQuery;
import cn.ronghuanet.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import sun.rmi.transport.ObjectTable;

import java.io.Serializable;
import java.util.List;
import java.util.Objects;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl implements IDepartmentService {
    @Autowired
    private DepartmentMapper mapper;

    @Transactional
    @Override
    public void insert(Department department) {

        mapper.insert(department);

        if (Objects.nonNull(department.getParent().getId())){
            // 根据这个父级的id 去查父级的对象 然后 父级对象的path 拼上自己的path
            Department parent = selectById(department.getParent().getId());
            department.setPath(parent.getPath()+"/"+department.getId());
        }else{
            // 父级id为空 表示自己是 一级部门
            department.setPath("/"+department.getId());
        }
        mapper.update(department);
    }

    @Transactional
    @Override
    public void update(Department department) {
        // 处理自己的path字段
        // 判断自己有没有父级
//        if (Objects.nonNull(department.getId())){
        if (Objects.nonNull(department.getParent().getId())){
            // 根据这个父级的id 去查父级的对象 然后 父级对象的path 拼上自己的path
            Department parent = selectById(department.getParent().getId());
            department.setPath(parent.getPath()+"/"+department.getId());
        }else{
            // 父级id为空 表示自己是 一级部门
            department.setPath("/"+department.getId());
        }
        mapper.update(department);
    }

    @Transactional
    @Override
    public void delete(Serializable id) {
        mapper.delete(id);
    }

    @Override
    public Department selectById(Serializable id) {
        return mapper.selectById(id);
    }

    @Override
    public List<Department> selectAll() {
        return mapper.selectAll();
    }

    @Override
    public PageInfo queryPage(DepartmentQuery departmentQuery) {
        // 查总数
        Long total = mapper.queryTotal(departmentQuery);
        if (total > 0){
            // 查数据
           List<Department> list = mapper.queryList(departmentQuery);
           return new PageInfo<Department>(total,list);
        }
        return new PageInfo<Department>();
    }

    @Override
    public void batchDelete(List<Long> ids) {
        mapper.batchDelete(ids);
    }

    @Override
    public List<Department> getDeptTree() {
        return mapper.getDeptTree();
    }
}
